package com.frogs.ucenter.v1.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.base.dao.BaseDao;
import com.frogs.framework.base.service.daoimpl.BaseServiceImpl;
import com.frogs.framework.util.file.FileUtil;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.AreaInfoDao;
import com.frogs.ucenter.entity.AreaInfo;
import com.frogs.ucenter.v1.request.AreaShowRequest;
import com.frogs.ucenter.v1.request.PostCodeRequest;
import com.frogs.ucenter.v1.request.SubAreaRequest;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.ListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.service.AreaInfoService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Service(ApiConstants.VERSION + "areaInfoService")
public class AreaInfoServiceImpl extends BaseServiceImpl<AreaInfo> implements
		AreaInfoService {

	@Resource
	private AreaInfoDao areaInfoDao;
	
	private static ResourceBundle ftpBundle;
	/** ftp配置路径 */
	private static final String ftpConfigPath = "ftp-config";
	
	private String basicPath;
	private String urlBasicPath;
	private String localPath;
	private String fileName;
	private String encode;
	private String ftpPath;
	
	
	public AreaInfoServiceImpl() {
		super();
		ftpBundle = PropertyResourceBundle.getBundle(ftpConfigPath);
		try {
			basicPath = ftpBundle.getString("js.basicPath");
			urlBasicPath = ftpBundle.getString("js.urlBasicPath");
			localPath = ftpBundle.getString("js.localPath");
			fileName = ftpBundle.getString("js.fileName");
			encode = ftpBundle.getString("js.fileEncoding");
		} catch (Exception e) {
			basicPath = ftpBundle.getString("basicPath");
			urlBasicPath = ftpBundle.getString("urlBasicPath");
			localPath = ftpBundle.getString("localPath");
			fileName = "commonArea.js";
			encode = "utf-8";
		}
		ftpPath = basicPath + urlBasicPath;
	}

	public AreaInfoDao getAreaInfoDao() {
		return areaInfoDao;
	}

	/**
	 * Don't remove or edit it.
	 */
	@Override
	protected BaseDao<AreaInfo> getBaseDao() {
		return areaInfoDao;
	}

	public void setAreaInfoDao(AreaInfoDao areaInfoDao) {
		this.areaInfoDao = areaInfoDao;
	}

	@Override
	public Response getSubAreaList(Request request) throws Exception {
		try {
			SubAreaRequest areaRequest = (SubAreaRequest) request;
			String parentId = areaRequest.getParentId();
			ListResponse<Map<String, String>> listResponse = new ListResponse<Map<String, String>>();
			listResponse.setList(areaInfoDao.getSubAreaList(parentId));
			return listResponse;
		} catch (Exception e) {
			log.error(
					"func[select] request[" + request + "] error["
							+ e.getMessage() + "]", e);
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	public Response getPostCode(Request request) throws Exception {
		try {
			PostCodeRequest areaRequest = (PostCodeRequest) request;
			String areaCode = areaRequest.getAreaCode();
			String address = areaRequest.getAddress();
			ShowResponse<String> response = new ShowResponse<String>();
			List<String> postCodeList = areaInfoDao.getPostCode(address,
					areaCode);
			if (postCodeList.size() > 0) {
				response.setInfo(postCodeList.get(0));
			}
			return response;
		} catch (Exception e) {
			log.error(
					"func[selectCode] request[" + request + "] error["
							+ e.getMessage() + "]", e);
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response showArea(Request request) throws Exception {
		AreaShowRequest asr = (AreaShowRequest) request;
		ShowResponse<AreaInfo> response = new ShowResponse<AreaInfo>();
		AreaInfo areaInfo = areaInfoDao.showArea(asr.getProvince(),
				asr.getCity(), asr.getDistrict());
		response.setInfo(areaInfo);
		return response;
	}

	/**
	 * 用于将所有地区信息输出到一个文件中，实现数据静态化
	 */
	@Override
	public Response createAreaFile(Request request,HttpServletRequest httpRequest) throws Exception {
		String parentId = "0";
		Response response = new DefaultResponse();
		try {
			List<Map<String, String>> areaList = loadAreas(parentId);
			exportFile(areaList,httpRequest);
			
		} catch (Exception e) {
			log.error(
					"func[selectCode] request[" + request + "] error["
							+ e.getMessage() + "]", e);
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		
		return response;
	}

	private List<Map<String, String>> loadAreas(String parentId)
			throws Exception {
		List<Map<String, String>> areaList = new ArrayList<Map<String, String>>();
		// 递归出口
		if (parentId.length() >= 6) {
			return areaList;
		}

		List<Map<String, String>> subList = areaInfoDao
				.getSubAreaList(parentId);
		for (Map<String, String> areaMap : subList) {
			areaMap.put("parentId", parentId);
			areaList.addAll(loadAreas(areaMap.get("areaCode")));
		}
		areaList.addAll(subList);

		return areaList;
	}
	
	// 写文件操作
	private void exportFile(Object areaList,HttpServletRequest request){
		String jsonStr = JSONObject.toJSONString(areaList);
		String ouputStr = "var areaAllJson=" + jsonStr;
		
		String filePath = FileUtil.getSaveFilePath(FileUtil.getRealPath(request), localPath,  fileName);
		
		FileUtil.writeToTextFile(filePath, ouputStr, encode);
		
	}
}